package yang.yu.sunny.datamodel;

import org.dayatang.domain.AbstractEntity;

import javax.persistence.*;
import java.util.*;

/**
 * 订单
 * Created by yyang on 16/3/15.
 */
@Entity
@Table(name = "order_data")
public class OrderData extends AbstractEntity {

    private Long customerId;

    @Temporal(TemporalType.TIMESTAMP)
    private Date created;

    private double totalPrice;

    public Long getCustomerId() {
        return customerId;
    }

    public void setCustomerId(Long customerId) {
        this.customerId = customerId;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    @Transient
    public List<OrderItemData> getItems() {
        return getRepository().findByProperty(OrderItemData.class, "orderId", getId());
    }

    public void setItems(Set<OrderItemData> items) {
        if (items == null) {
            totalPrice = 0;
            return;
        }
        items.stream().forEach(orderItem -> {
            orderItem.setOrderId(getId());
            //orderItem.save();
        });
        totalPrice = items.stream().mapToDouble(OrderItemData::getTotalPrice).sum();
    }

    public static OrderData get(Long id) {
        return getRepository().get(OrderData.class, id);
    }
}
